UNPKG

2.32 kBJavaScriptView Raw
1import path from 'path'
2
3import serialize from './tools/serialize-javascript'
4
5import { exists } from './helpers'
6
7// returns a stub for webpack-assets.json if it doesn't exist yet
8// (because node.js and webpack are being run in parallel in development mode)
9export function default_webpack_assets()
10{
11 const webpack_assets =
12 {
13 javascript: {},
14 styles: {},
15 assets: {}
16 }
17
18 return webpack_assets
19}
20
21// adds missing fields, etc
22export function normalize_options(options)
23{
24 // if no assets specified (for whatever reason), make it an empty array
25 if (!options.assets)
26 {
27 options.assets = {}
28 // throw new Error('You must specify "assets" parameter')
29 }
30
31 // webpack-assets.json path, relative to the project base path
32 options.webpack_assets_file_path = options.webpack_assets_file_path || 'webpack-assets.json'
33
34 // generate names (if required) for each user defined asset type, normalize extensions
35 for (let asset_type of Object.keys(options.assets))
36 {
37 const description = options.assets[asset_type]
38
39 // normalize extensions
40 if (description.extension)
41 {
42 // sanity check
43 if (Array.isArray(description.extension))
44 {
45 throw new Error(`Use "extensions" key instead of "extension" for specifying an array of file extensions for assets of type "${asset_type}"`)
46 }
47
48 // normalize
49 description.extensions = [description.extension]
50 delete description.extension
51 }
52
53 // sanity check
54 if (!description.extensions)
55 {
56 throw new Error(`You must specify file extensions for assets of type "${asset_type}"`)
57 }
58 }
59}
60
61// returns a CommonJS modules source.
62export function to_javascript_module_source(source)
63{
64 // if the asset source wasn't found - return an empty CommonJS module
65 if (!exists(source))
66 {
67 return 'module.exports = undefined'
68 }
69
70 // if it's already a common js module source
71 if (typeof source === 'string' && is_a_module_declaration(source))
72 {
73 return source
74 }
75
76 // generate javascript module source code based on the `source` variable
77 return 'module.exports = ' + serialize(source)
78}
79
80// detect if it is a CommonJS module declaration
81function is_a_module_declaration(source)
82{
83 return source.indexOf('module.exports = ') === 0 ||
84 /\s+module\.exports = .+/.test(source)
85}
\No newline at end of file